var index;

var table;
var form;

var householdPositionId;
var householdPositionName;

$(document).ready(function () {
    $('#page-toolbar-content').show();

    layui.use(['table', 'form'], function () {

        table = layui.table;
        form = layui.form;
        form.render();

        getAllButton(currUrl).done(function(returnData) {
            createButton(returnData);
            initButtonEvent();
            initTable();
        });

    });

});

function initButtonEvent() {

    var $ = layui.$, active = {

        add: function () {
            loadingChildPage('/admin/personnel/personnel_add', '新增人员');
        },
        edit: function () {
            var checkStatus = table.checkStatus('personnel-table-content');
            var data = checkStatus.data;
            if (data.length <= 0) {
                layer.msg("没有选取任何行！");
            }
            else if (data.length > 1) {
                layer.msg("无法批量修改行！");
            }
            else {
                loadingChildPageId('/admin/personnel/personnel_edit', '编辑人员', data[0].householdId);
            }
        },
        del: function () {
            var checkStatus = table.checkStatus('personnel-table-content');
            var data = checkStatus.data;
            if (data.length <= 0) {
                layer.msg("没有选取任何行！");
            }
            else {
                var dataIds = [];
                for (var i = 0; i < data.length; i++) {
                    dataIds[i] = data[i].householdId;
                }

                removePersonnel(dataIds);
            }
        },
        search: function () {

            var householdName = $('#householdName');
            var positionName = $('#positionName');

            // 执行重载
            table.reload('personnel-table-content', {
                page: {
                    curr: 1
                }
                , where: {
                    householdName: householdName.val(),
                    positionName: positionName.val()
                }
            });

            $('.layui-table-page').css('text-align', 'right');
            $('.layui-table-page').css('padding-right', '20px');

        }
    };

    $('.menu-btn-group .layui-btn, .layui-btn').on('click', function () {
        var type = $(this).data('type');
        active[type] ? active[type].call(this) : '';
    });

}

function initTable() {

    table.render({
        elem: '#personnel-table-content'
        , url: apiHostUrl + '/admin/personnel/queryPersonnel'
        , headers: {Authorization: token}
        , response: {
            statusName: 'errorCode'
            , statusCode: 0
            , msgName: 'errorMsg'
            , countName: 'totalCount'
            , dataName: 'returnData'
        }
        , cellMinWidth: 50
        , limit: 15
        , limits: [15]
        , cols: [[
            {type: 'checkbox'}
            , {field: 'householdId', width: 70, title: 'ID'}
            , {field: 'householdNo', width: 130, title: '员工号'}
            , {field: 'householdName', width: 100, title: '姓名'}
            , {field: 'householdSexString', width: 60, title: '性别'}
            , {field: 'householdPositionName', width: 110, title: '部门'}
            , {field: 'householdPhone', width: 130, title: '手机号码'}
            , {field: 'householdEmail', width: 160, title: '电子邮箱'}
            , {field: 'householdIDCard', width: 180, title: '身份证号'}
            , {field: 'householdJob', width: 80, title: '职业'}
            , {field: 'householdAge', width: 70, title: '年龄'}
            , {field: 'householdEducation', width: 70, title: '学历'}
            , {field: 'householdHobby', title: '兴趣爱好'}
            , {field: 'householdCreateTime', width: 170, title: '入职时间'}
            , {field: 'toolbar', width: 180, title: '操作', align: 'center', toolbar: '#tableToolbar'}
        ]]
        , page: {
            layout: ['prev', 'page', 'next', 'skip', 'limit', 'count']
        }
        , id: 'personnel-table-content'
    });

    // 监听工具条
    table.on('tool(page-table)', function (obj) {
        var data = obj.data;
        if (obj.event === 'del') {
            var dataIds = [];
            dataIds[0] = data.householdId;
            removePersonnel(dataIds);
        } else if (obj.event === 'edit') {
            loadingChildPageId('/admin/personnel/personnel_edit', '编辑人员', data.householdId);
        }
    });

    $('.layui-table-page').css('text-align', 'right');
    $('.layui-table-page').css('padding-right', '20px');

}

function removePersonnel(householdIds) {
    layer.confirm("真的要删除该行吗？", function () {
        ajax(
            "/admin/personnel/delPersonnel", "POST",
            {householdIds: householdIds}
            , true, true, true
        ).done(function () {
            loadingPage("/admin/personnel/personnel");
        });
        layer.closeAll();
    });
}

function chooseParentPosition() {

    index = layer.open({
        title: "选择部门",
        type: 1,
        id: 'layer-page-page',
        shade: 0,
        area: ['330px', '652px'],
        tipsMore: false,
        content:
        '<div style="text-align: center;"></div><div id="personnel-parent-tree" style="padding: 20px;min-height: 500px;max-height: 500px;"></div>' +
        '<hr>' +
        '<div class="layui-form-item" style="text-align: center;margin-bottom: 5px;">' +
        '<button class="layui-btn layui-btn-default"><i class="fa fa-check fa-fw" onclick="javascript:layer.close(index);"></i>确认</button>' +
        '<button class="layui-btn layui-btn-danger" onclick="javascript:layer.close(index);"><i class="fa fa-reply fa-fw"></i>返回</button></div></div>',
        success: function (alertLayer) {
            var btn_ok = alertLayer.find('.layui-btn-default');
            btn_ok.attr({
                onclick: "javascript:setParentPosition();"
            });
            var btn_cancel = alertLayer.find('.layui-btn-danger');
            btn_cancel.attr({
                onclick: 'layer.closeAll();'
            });
        }
    });

    getAllParentPositionTreeData();
}

function getAllParentPositionTreeData() {

    ajax(
        "/admin/position/getParentPositionTree", "POST",
        { positionTypes : [1] },
        true, true, false
    ).done(function (returnData) {

        $('#personnel-parent-tree').bind("activate_node.jstree", function (obj, e) {
            // 得到被点击节点的id
            householdPositionId = e.node.id;
            householdPositionName = e.node.text;
        });

        createParentJSTree(returnData);
    });

}

function setParentPosition() {

    layer.closeAll();
    var householdPositionIdInput = $("#householdPositionId");
    householdPositionIdInput.val(householdPositionId);
    var householdPositionNameInput = $("#householdPositionName");
    householdPositionNameInput.val(householdPositionName);
}

function createParentJSTree(jsonData) {

    var tree = $('#personnel-parent-tree');

    tree.jstree({
        core: {
            multiple: false,
            themes: {
                responsive: !1,
            },
            data: jsonData
        },
        types: {
            "default": {
                icon: "fa fa-copyright icon-state-default icon-lg"
            },
            file: {
                icon: "fa fa-sitemap icon-state-default icon-lg"
            }
        },
        plugins: ["types", "state", "checkbox"]
    });

    tree.jstree(true).settings.core.data = jsonData;
    tree.jstree(true).refresh();

}